import { getMd5Sign } from '../../utils/util'
const request = require('../config/index')

/**
 * 获取已拥有优惠券列表
 * @param type
 * @param page
 * @param size
 * @param use_money
 */
export const getAlreadyOwnedCoupons = (type: string, page: string, size: string, use_money = null) => {
    const openid = wx.getStorageSync('openid')
    let body: any
    if (typeof use_money == 'object') {
        body = {
            API_Model: 'Coupon',
            API_Name: 'Get_User_Coupon',
            Data: {
                user_openid: openid,
                page: page, //分页页码，数字类型
                size: size, //分页参数 一页多少条数据
                type: type + '' //优惠券状态 1未使用 2已使用 3已过期
            }
        }
    } else {
        body = {
            API_Model: 'Coupon',
            API_Name: 'Get_User_Coupon',
            Data: {
                user_openid: openid,
                page: page, //分页页码，数字类型
                size: size, //分页参数 一页多少条数据
                type: type + '', //优惠券状态 1未使用 2已使用 3已过期
                use_money: use_money
            }
        }
    }

    const md5 = getMd5Sign(body)
    return new Promise((resolve, reject) => {
        request
            .post(`/api/doAPI`, body, {
                sign: md5
            })
            .then((res: any) => {
                resolve(res.data)
            })
            .catch((err: any) => {
                reject(err)
            })
    })
}

/**
 * 领取优惠券
 * @param id
 */
export const receiveACoupon = (id: string) => {
    const openid = wx.getStorageSync('openid')
    const body = {
        API_Model: 'Coupon',
        API_Name: 'Get_Coupon',
        Data: {
            user_openid: openid,
            coupon_id: id
        }
    }
    const md5 = getMd5Sign(body)
    return new Promise((resolve, reject) => {
        request
            .post(`/api/doAPI`, body, {
                sign: md5
            })
            .then((res: any) => {
                resolve(res.data.data)
            })
            .catch((err: any) => {
                reject(err)
            })
    })
}

/**
 * 获取可以领取的优惠卷
 * @param page 当前第几页
 * @param size 一页多少条
 */
export const getACouponAvailable = (page: number, size: number) => {
    const body = {
        API_Model: 'Coupon',
        API_Name: 'Get_Function_Coupon',
        Data: {
            page, //分页参数 当前第几页
            size //分页参数 一页多少条
        }
    }
    const md5 = getMd5Sign(body)
    return new Promise((resolve, reject) => {
        request
            .post(`/api/doAPI`, body, {
                sign: md5
            })
            .then((res: any) => {
                resolve(res.data)
            })
            .catch((err: any) => {
                reject(err)
            })
    })
}
